package com.noyes4j.device.controller;

import com.alibaba.fastjson.JSONObject;
import com.noyes4j.common.core.controller.BaseController;
import com.noyes4j.common.core.domain.R;
import com.noyes4j.common.utils.StringUtils;
import com.noyes4j.common.utils.airkiss.AirKissUtil;
import com.noyes4j.common.utils.airkiss.Base64Util;
import com.noyes4j.common.utils.airkiss.HttpUtil;
import com.noyes4j.common.utils.airkiss.JsApiConfigModel;
import com.noyes4j.common.utils.qr.QRCodeUtil;
import com.noyes4j.device.domain.SysDevice;
import com.noyes4j.device.service.ISysDeviceService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Date;
import java.util.List;

/**
* @Description:    HandleDeviceController
* @Author:         luoyhong
* @CreateDate:     2021/2/3 17:57
* @UpdateUser:     luoyhong
* @UpdateDate:     2021/2/3 17:57
* @UpdateRemark:   修改内容
* @Version:        1.0
*/
@Controller
@RequestMapping("/wxAirKiss")
public class HandleDeviceController extends BaseController {

    private static Logger logger = LoggerFactory.getLogger(HandleDeviceController.class);

    @Value(value="${app.zntd.property.appid}")
    private String appid;
    @Value(value="${app.zntd.property.appsecret}")
    private String appsecret;
    @Value(value="${app.zntd.property.accessTokenUrl}")
    private String accessTokenUrl;
    @Value(value="${app.zntd.property.prefixTicketUrl}")
    private String prefixTicketUrl;
    @Value(value="${app.zntd.property.proId}")
    private long proId;

    @Autowired
    private ISysDeviceService sysDeviceService;

    /**
     * @function    获取airkiss配置的基本信息
     * @author      luoyhong
     * @param wifiSsid
    * @param wifiPwd
    * @param jsCode
    * @param request
     * @return      com.noyes4j.common.core.domain.R
     * @exception
     * @date        2021/2/4 14:13
     */
    @PostMapping("/getAirKissConfigData")
    @ResponseBody
    @CrossOrigin
    public R getAirKissConfigData(@RequestParam("wifiSsid") String wifiSsid,@RequestParam("wifiPwd") String wifiPwd,@RequestParam("jsCode") String jsCode){

        try{
            if(StringUtils.isEmpty(jsCode)){
                return R.error("jsCode can not be empty");
            }
            String openid = AirKissUtil.getOpenId(jsCode,appid,appsecret);
            if(StringUtils.isEmpty(openid)){
                return R.error("get openid is error");
            }
/*

            boolean addFlag = true;
            String accessToken = null;
            String apiTicket = null;

            SysDevice sysDevice = new SysDevice();
            sysDevice.setOpenid(openid);
            List<SysDevice> sysDeviceList = sysDeviceService.selectSysDeviceList(sysDevice);
            if(sysDeviceList!=null&&sysDeviceList.size()>=1){
                accessToken = sysDeviceList.get(0).getToken();
                apiTicket = sysDeviceList.get(0).getTicket();
                addFlag = false;
            }
            if(StringUtils.isEmpty(accessToken)){
                accessToken = AirKissUtil.getAccessToken(accessTokenUrl);
            }
            if(StringUtils.isEmpty(accessToken)){
                return R.error("get access_token error");
            }

            if(StringUtils.isEmpty(apiTicket)){
                apiTicket = AirKissUtil.getApiTicket(prefixTicketUrl,accessToken,accessTokenUrl);
            }
            if (StringUtils.isEmpty(apiTicket)) {
                return R.error("get ticket error");
            }

            String nonceStr = AirKissUtil.getRandomString(16);
            if(StringUtils.isBlank(nonceStr)){
                return R.error("get nonceStr error");
            }

            String localurl = request.getRequestURL().toString();
            //String timeStamp =  System.currentTimeMillis() / 1000 + "";
            String timeStamp =  System.currentTimeMillis()+"";
            String key = "jsapi_ticket=" + apiTicket
                    + "&noncestr=" + nonceStr
                    + "&timestamp=" + timeStamp
                    + "&url=" + localurl;
            String sign = AirKissUtil.hash(key, "SHA1");

            if(StringUtils.isBlank(sign)){
                return R.error("get sign error");
            }

            Date data = new Date();
            sysDevice = new SysDevice();
            sysDevice.setOpenid(openid);
            sysDevice.setToken(accessToken);
            sysDevice.setTicket(apiTicket);
            sysDevice.setUpdateTime(data);
            if(addFlag){
                sysDevice.setProId(proId);
                sysDevice.setCreateTime(data);
                sysDeviceService.insertSysDevice(sysDevice);
            }else{
                sysDeviceService.updateSysDevice(sysDevice);
            }
*/

            JSONObject qrJson =  new JSONObject();
            qrJson.put("s",wifiSsid);
            qrJson.put("p",wifiPwd);
            qrJson.put("o",openid);
            String qrContent = Base64Util.encode(qrJson.toJSONString());
            String qrcodePath  = QRCodeUtil.getPathByCodeCreate( qrContent,  QRCodeUtil.iotQrCodeBasePath,  null,  QRCodeUtil.logoPath) ;
            qrcodePath = qrcodePath.replace(QRCodeUtil.iotQrCodeBasePath,"");
            return R.data(qrcodePath);

        }catch (Exception e){
            logger.error(e.getMessage());
            return R.error(e.getMessage());
        }

    }

    /**
     * @function    根据路径获取二维码
     * @author      luoyhong
     * @param path
    * @param response
     * @return      void
     * @exception
     * @date        2021/1/29 14:11
     */
    @GetMapping("/getAirKissQrCode")
    @CrossOrigin
    public void getAirKissQrCode(String path, HttpServletResponse response){

        try{
            if(path!=null&&!"".equals(path)){
                path = QRCodeUtil.iotQrCodeBasePath+path;
                File file = new File(path);
                if(file.exists()){ //判断文件父目录是否存在
                    //提取文件名
                    int index = path.lastIndexOf("/")<0?0:path.lastIndexOf("/");
                    String filename=path.substring(index,path.length());

                    response.setContentType("img/jpg");
                    response.setCharacterEncoding("utf-8");
                    byte[] buffer = new byte[1024];
                    FileInputStream fis = null; //文件输入流
                    BufferedInputStream bis = null;

                    OutputStream os = null; //输出流
                    try {
                        os = response.getOutputStream();
                        fis = new FileInputStream(file);
                        bis = new BufferedInputStream(fis);
                        int length;
                        while ((length = bis.read(buffer)) > 0)
                        {
                            os.write(buffer, 0, length);
                        }
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                        logger.error(e.getMessage());
                    }
                    try {
                        bis.close();
                        fis.close();
                        file.delete();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                        logger.error(e.getMessage());
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error(e.getMessage());
        }
    }

    /**
     * @function    处理设备的请求信息
     * @author      luoyhong
     * @param msg
    * @param request
     * @return      com.alibaba.fastjson.JSONObject
     * @exception
     * @date        2021/1/29 14:15
     */
    @PostMapping("/handleIotDeviceMsg")
    @ResponseBody
    @CrossOrigin
    public JSONObject handleIotDeviceMsg(@RequestBody String msg, HttpServletRequest request){

        JSONObject jsonObject = new JSONObject();
        return jsonObject;
    }

    @PostMapping("/postTest")
    @ResponseBody
    @CrossOrigin
    public R postTest(@RequestBody String msg){

        return R.ok(msg);
    }

    @GetMapping("/getTest")
    @ResponseBody
    public R getTest(String msg){

        return R.ok(msg);
    }

    /**
     * @function    将设备与微信绑定
     * @author      luoyhong
     * @param sn
    * @param openid
    * @param request
    * @param opType
     * @return      com.alibaba.fastjson.JSONObject
     * @exception
     * @date        2021/2/3 17:13
     */
    @PostMapping("/bindDeviceWithWechat")
    @ResponseBody
    //@CrossOrigin
    public R bindDeviceWithWechat(@RequestParam("sn") String sn,@RequestParam("openid") String openid) {

        R result = R.error("bindDeviceWithWechat is error");
        try{
            if(!StringUtils.isEmpty(sn)&&!StringUtils.isEmpty(openid)){
                boolean addFlag = false;
                SysDevice sysDevice= new SysDevice();
                sysDevice.setSn(sn);
                sysDevice.setOpenid(openid);
                List<SysDevice> sysDeviceList = sysDeviceService.selectSysDeviceList(sysDevice);
                if(sysDeviceList==null||sysDeviceList.size()<=0){
                    addFlag = true;
                }
                Date data = new Date();
                sysDevice = new SysDevice();
                sysDevice.setOpenid(openid);
                sysDevice.setSn(sn);
                sysDevice.setUpdateTime(data);
                if(addFlag){
                    sysDevice.setProId(proId);
                    sysDevice.setCreateTime(data);
                    sysDeviceService.insertSysDevice(sysDevice);
                }else{
                    sysDeviceService.updateSysDevice(sysDevice);
                }
                result = R.ok("ok");
            }else{
                result = R.error("param is error");
            }
        }catch (Exception e){
            logger.error(e.getMessage());
            result = R.error(e.getMessage());
        }
        return result;
    }

    public R handleDeviceWithWechat(Integer opType,String sn,String openid){

        R r = R.error("handleDeviceWithWechat error");
        try {

            if(opType!=null){
                //根据设备信息查找对应存贮在数据库中的数据
                SysDevice sysDevice= new SysDevice();
                sysDevice.setSn(sn);
                sysDevice.setOpenid(openid);
                List<SysDevice> sysDeviceList = sysDeviceService.selectSysDeviceList(sysDevice);
                if(sysDeviceList==null||sysDeviceList.size()<=0){
                    return R.error("can not find the device info from database");
                }else{
                    sysDevice = sysDeviceList.get(0);
                }
                String ticket = sysDevice.getTicket();
                String accessToken = sysDevice.getToken();
                if(StringUtils.isEmpty(ticket)||StringUtils.isEmpty(accessToken)){
                    return R.error("ticket or access_token can not be empty");
                }
                String url = "";
                switch (opType){
                    case 0:{//绑定
                        url = "https://api.weixin.qq.com/device/bind?access_token="+accessToken;
                        break;
                    }
                    case 1:{//强制绑定
                        url = "https://api.weixin.qq.com/device/compel_bind?access_token="+accessToken;
                        break;
                    }
                    case 2:{//解绑
                        url = "https://api.weixin.qq.com/device/unbind?access_token="+accessToken;
                        break;
                    }
                    case 3:{//强制解绑
                        url = "https://api.weixin.qq.com/device/compel_unbind?access_token="+accessToken;
                        break;
                    }
                    default:{
                        break;
                    }
                }
                if(StringUtils.isEmpty(url)){
                    return R.error("opType invalid");
                }
                JSONObject param = new JSONObject();
                param.put("ticket",ticket);
                param.put("device_id",sn);
                param.put("openid",openid);
                String result = HttpUtil.doPost(url,param.toJSONString());

                if(!StringUtils.isEmpty(result)){
                    JSONObject js1 = JSONObject.parseObject(result);
                    js1 = js1.getJSONObject("base_resp");
                    if(js1!=null){
                        if(0==js1.getInteger("errcode")){
                            r = R.ok(js1.getString("errmsg"));
                        }else{
                            r = R.error(js1.getString("errmsg"));
                        }
                    }
                }
            }
        }catch (Exception e){
            logger.error(e.getMessage());
            r = R.error(e.getMessage());
        }
        return r;
    }

}
